<!--suppress TypeScriptUnresolvedReference -->
<script setup lang="ts">
import { ref } from "vue"
import { cartData, commentData, itemData, updateCartData } from "@/api/items/types/types"
import { addToCartDataApi, getCartDataApi, getItemDataApi, updateCartDataApi, getCommentApi } from "@/api/items/items"
import { useRoute, useRouter } from "vue-router"
import { ElMessage } from "element-plus"
import Layout from "@/views/layout/Layout.vue"
import Comments from "@/views/catalog/components/comment.vue"

const loading = ref(true)
const addButtonFlag = ref(false)
const itemStar = ref(0)
itemStar.value = Number((Math.random() * 5).toFixed(1))
const colors = ref(["#99A9BF", "#F7BA2A", "#FF9900"]) // same as { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }
const categoryId = useRoute().params.categoryId
const item = ref<itemData>({
  itemId: "",
  image: "",
  product: {
    productId: "",
    name: "",
    category: ""
  },
  attribute1: "",
  listPrice: ""
})
const itemId = useRoute().params.itemId.toString()
const cartItems = ref<cartData[]>([])
const comment = ref<commentData[]>([])
const getCartItems = () => {
  loading.value = true
  getCartDataApi("HHHH")
    .then((res) => {
      cartItems.value = res.data
      loading.value = false
    })
    .catch((err) => {
      console.log(err)
    })
}
getCartItems()
const getItem = () => {
  loading.value = true
  getItemDataApi(itemId)
    .then((res) => {
      item.value = res.data
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      loading.value = false
    })
}
getItem()
const updateCart = (itemId: string, quantity: number, userid: string) => {
  if (quantity == 0) {
    cartItems.value.filter((item) => {
      return item.itemDTO.itemId != itemId
    })
  }
  const data: updateCartData = {
    userid: userid,
    itemid: itemId,
    quantity: quantity
  }
  updateCartDataApi(data).then((res) => {
    if (res.message === "SUCCESS") {
      ElMessage.success("成功修改数量！")
    } else {
      ElMessage.error("修改数量失败！")
    }
  })
}

const formatListPrice = (listPrice) => {
  return "￥" + Number(listPrice).toFixed(2)
}
const addItem = (itemId: string, quantity: number, userid: string) => {
  addButtonFlag.value = true
  setTimeout(() => {
    const data: updateCartData = {
      userid: userid,
      itemid: itemId,
      quantity: quantity
    }
    cartItems.value.at(cartItems.value.findIndex((item) => item.itemDTO.itemId == itemId)).quantity = 1
    addToCartDataApi(data).then((res) => {
      if (res.message === "SUCCESS") {
        ElMessage.success("成功添加到购物车！")
      } else {
        ElMessage.error("添加到购物车失败！")
      }
      addButtonFlag.value = false
    })
  }, 500)
}
</script>

<template>
  <layout>
    <div class="item">
      <el-image class="pet-item-photo" :src="item.image" fit="fill" />
      <h2 class="pet-name">
        <a>{{ item.itemId }}</a>
        <span class="species">{{ categoryId.slice(0, categoryId.length - 1) }}</span>
      </h2>
      <el-rate v-model="itemStar" disabled show-score text-color="#ff9900" :colors="colors" score-template="{value}" />
      <p><strong>Product ID</strong>{{ item.product.productId }}</p>
      <p><strong>Description</strong> {{ item.attribute1 }}{{ item.product.name }}</p>
      <p>
        <strong>List Price:</strong>
        <el-text type="warning" size="large">{{ formatListPrice(item.listPrice) }}</el-text>
      </p>
      <p
        v-if="
          !(
            cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId) === -1 ||
            cartItems.at(cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId)).quantity === 0
          )
        "
      >
        <strong>Total Price:</strong>
        <el-text type="warning" size="large">{{
          formatListPrice(
            item.listPrice * cartItems[cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId)].quantity
          )
        }}</el-text>
      </p>
      <el-button
        type="primary"
        :loading="addButtonFlag"
        style="margin-top: 50px"
        @click="addItem(item.itemId, 1, 'HHHH')"
        v-if="
          cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId) === -1 ||
          cartItems.at(cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId)).quantity === 0
        "
        >Add to Cart</el-button
      >
      <el-input-number
        style="margin-top: 21.4px"
        v-model="cartItems[cartItems.findIndex((x) => x.itemDTO.itemId === item.itemId)].quantity"
        v-else
        @change="updateCart(item.itemId, $event, 'HHHH')"
      />
    </div>
    <div class="item" @average="(average:number)=>itemStar=average">
      <h2>商品评价</h2>
      <!--      <el-table :data="comment" style="width: 100%">
        <el-table-column prop="userid" label="User ID" width="180" />
        <el-table-column prop="rating" label="Rating" width="180" />
        <el-table-column prop="comment" label="Comment" />
      </el-table>-->
      <Comments />
    </div>
  </layout>
</template>

<style scoped>
/*商品具体页面*/
.item {
  position: relative;
  max-width: 1200px;
  padding: 20px;
  margin: 30px auto;
  background-color: #fff;
  box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.item h4 {
  margin: 0 0 6px 0;
}
.item p {
  font-size: 16px;
  padding-bottom: 3px;
}
.commentButton {
  margin-left: 8%;
  height: 50px;
  width: 100px;
  background: linear-gradient(to right, #ff9000, #ff7000);
  color: white;
  border-radius: 50px;
  border: none;
}
.commentButton:hover {
  cursor: pointer;
  opacity: 0.8;
}
.pet-item-photo {
  width: 464px;
  height: 332px;
  float: left;
  /*width: 40%;*/
  margin-right: 15px;
}

.pet-name {
  font-size: 2rem;
  font-weight: normal;
  margin: 0 0 1rem 0;
}

.species {
  font-size: 0.9rem;
  color: #888;
  vertical-align: middle;
}
</style>
